import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { authAPI, userAPI } from '../services/api';
import './styles.css';

function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [userid, setUserid] = useState(''); // 添加userid字段
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  
  const navigate = useNavigate();
  const location = useLocation();

  // 检查是否是从注册页面跳转过来的
  useEffect(() => {
    if (location.state?.message) {
      setSuccessMessage(location.state.message);
      if (location.state.email) {
        setEmail(location.state.email);
      }
    }
  }, [location]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccessMessage('');
    setLoading(true);
    
    try {
      // 构建请求数据
      const loginData = {
        
        email,
        password,
        userid
      };
     
      
      // 调用登录API
      const response = await authAPI.login(loginData);
      
      // 处理响应
      if (response) {
        // 存储用户信息和token
        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('token', response.result.token);
        localStorage.setItem('userData', JSON.stringify(response.result));
      
        try {
          // 检查是否有userid
          const responseUserid = response.result.userId;
          console.log('登录响应中的userid:', responseUserid);
          if (!responseUserid) {
            throw new Error('登录响应中缺少userid');
          }
          
           const userInfoId = 
           {
             userId: String(response.result.userId)
           };

           console.log('userInfoId:',userInfoId);
          
          // 使用userId获取用户信息
          //出错在这
          const userInfoResponse = await userAPI.getUserInfo(userInfoId);
          // 如果获取不到用户信息或信息不完整，说明是第一次登录，跳转到信息设置页面
          const isFirstLogin = !userInfoResponse.result;
          console.log('用户信息:', userInfoResponse, '是否第一次登录:', isFirstLogin, '使用的标识符:', responseUserid);
          
          if (isFirstLogin) {
            // 第一次登录，跳转到信息设置页面
            navigate('/user-info-setup', {
              state: {
                userid: response.result.userId, // 只使用userId
                firstLogin: true
              }
            });
          } else {
            // 非第一次登录，跳转到仪表板
            navigate('/dashboard');
          }
        } catch (infoErr) {
          console.error('获取用户信息失败:', infoErr);
          if (infoErr.message === '登录响应中缺少userid') {
           
          }
         
          // 如果获取信息失败，假设是第一次登录
          navigate('/user-info-setup', {
            state: {
              userId: response.result.userId, // 只使用userId
              firstLogin: true,
              error: '无法验证用户信息状态'
            }
          });
        }
      } else {
        
        setError('登录失败：未获取到有效的用户数据');
      }
      
    } catch (err) {
      setError('登录失败: ' + (err.response?.data?.message || err.message || '请检查您的凭据'));
      setLoading(false);
    }
  };

  const navigateToRegister = () => {
   
    navigate('/register');
  };

  return (
    <div className="auth-container">
      <div className="auth-card">
        <h2>用户登录</h2>
        
        {error && <div className="error-message">{error}</div>}
        {successMessage && <div className="success-message">{successMessage}</div>}
        
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="email">邮箱</label>
            <input
              type="email"
              id="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              placeholder="请输入您的邮箱"
              autoComplete="email"
            />
          </div>
          
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              placeholder="请输入密码"
              autoComplete="current-password"
            />
          </div>
          
          <div className="form-actions">
            <button 
              type="submit" 
              className="btn-primary"
              disabled={loading}
            >
              {loading ? '登录中...' : '登录'}
            </button>
            
            <button 
              type="button" 
              className="btn-secondary"
              onClick={navigateToRegister}
            >
              注册账号
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default Login;
